package org.viva.service.wx.mp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.viva.core.Log;
import org.viva.entity.wx.Token;
import org.viva.util.wx.WXBizMsgCrypt;

import net.sf.json.JSONObject;

@Service
public class AccessTokenService {
    private static final int readTimeOut    = 10 * 1000;
    private static final int connectTimeout = 10 * 1000;

    @Resource
    private WxConfigServiceImpl weiXinConfigService;

    public final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
    public final String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    private Token accessToken;
    private Token ticket;

    public Token getToken() {
        if (accessToken == null) {
            up();
        }
        if (accessToken.isTimeout()) {
            up();
        }
        return accessToken;
    }

    public Token getTicket() {
        if (ticket == null) {
            upTicket();
        }
        if (ticket.isTimeout()) {
            upTicket();
        }
        return ticket;
    }

    private void up() {
        Token accessToken = null;
        WXBizMsgCrypt wxBizMsgCrypt = weiXinConfigService.getWxBizMsgCrypt();
        String requestUrl = ACCESS_TOKEN_URL.replace("APPID", wxBizMsgCrypt.getAppId()).replace("SECRET", wxBizMsgCrypt.getAppSecret());
        String re = doGet(requestUrl);
        System.out.println(re);
        // 如果请求成功
        if (null != re) {
            JSONObject jsonObject = JSONObject.fromObject(re);
            try {
                accessToken = new Token();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
                accessToken.setGetTime(System.currentTimeMillis());
                this.accessToken = accessToken;
                System.out.println("获取token成功:" + jsonObject.getString("access_token") + "————" + jsonObject.getInt("expires_in"));
            } catch (Exception e) {
                String error = String.format("获取token失败 errcode:{%s} errmsg:{%s}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                Log.error(error, e);
            }
        }
    }

    private void upTicket() {
        Token accessToken = null;
        String requestUrl = JSAPI_TICKET_URL.replace("ACCESS_TOKEN", getToken().getToken());
        String re = doGet(requestUrl);
        // 如果请求成功
        if (null != re) {
            JSONObject jsonObject = JSONObject.fromObject(re);
            try {
                accessToken = new Token();
                accessToken.setToken(jsonObject.getString("ticket"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
                accessToken.setGetTime(System.currentTimeMillis());
                this.ticket = accessToken;
                System.out.println("获取jsapi_ticket成功:" + jsonObject.getString("ticket") + "————" + jsonObject.getInt("expires_in"));
            } catch (Exception e) {
                String error = String.format("获取jsapi_ticket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
                Log.error(error, e);
            }
        }
    }

    // 向服务器发送get请求
    public static String doGet(String urlAddress) {
        try {
            Log.debug("url : " + urlAddress);
            URL url = new URL(urlAddress);
            HttpURLConnection uRLConnection = (HttpURLConnection) url.openConnection();
            uRLConnection.setRequestMethod("GET");
            uRLConnection.setReadTimeout(readTimeOut);
            uRLConnection.setConnectTimeout(connectTimeout);
            return getResponse(uRLConnection);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getResponse(HttpURLConnection uRLConnection) throws IOException {
        InputStream is = uRLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String response = "";
        String readLine = null;
        while ((readLine = br.readLine()) != null) {
            response = response + readLine;
        }
        uRLConnection.disconnect();
        is.close();
        br.close();

        return response;
    }

    public Map<String, String> sign(String url) {
        String jsapi_ticket = getTicket().getToken();
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        WXBizMsgCrypt wxBizMsgCrypt = weiXinConfigService.getWxBizMsgCrypt();
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", wxBizMsgCrypt.getAppId());
        ret.put("debug", wxBizMsgCrypt.isDebug() + "");
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
